<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>我的订单</p>
    </header>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      <p>加载订单失败，请重试</p>
      <button @click="reloadOrders">重新加载</button>
    </div>
    
    <!-- 空状态 -->
    <div v-else-if="(orderArr || []).length === 0" class="empty">
      <img src="https://picsum.photos/200/200?random=1" alt="暂无订单" />
      <p>暂无订单</p>
    </div>
    
    <!-- 订单列表部分 -->
    <div v-else>
      <h3>未支付订单信息：</h3>
      <ul class="order">
        <li v-for="item in filterOrders(0)" :key="item.id || item.orderId">
          <div class="order-info">
            <p>
              {{getBusinessName(item)}}
              <i class="fa fa-caret-down" @click="detailetShow(item)"></i>
            </p>
            <div class="order-info-right">
              <p>¥{{item.orderTotal || 0}}</p>
              <div class="order-info-right-icon" @click="goPay(item)">去支付</div>
            </div>
          </div>
          <ul class="order-detailet" v-show="item.isShowDetailet">
            <li v-for="odItem in item.list || []" :key="odItem.id || odItem.foodId">
              <p>{{getFoodName(odItem)}} x {{odItem.quantity || 0}}</p>
              <p>¥{{getFoodTotalPrice(odItem)}}</p>
            </li>
            <li>
              <p>数量</p>
              <p>¥{{item.business?.deliveryPrice || 0}}</p>
            </li>
          </ul>
        </li>
      </ul>

      <h3>已支付订单信息：</h3>
      <ul class="order">
        <li v-for="item in filterOrders(1)" :key="item.id || item.orderId">
          <div class="order-info">
            <p>
              {{getBusinessName(item)}}
              <i class="fa fa-caret-down" @click="detailetShow(item)"></i>
            </p>
            <div class="order-info-right">
              <p>¥{{item.totalPrice || 0}}</p>
              <div class="order-info-right-icon evaluate-btn" @click="showEvaluateModal(item)">评价</div>
            </div>
          </div>
          <ul class="order-detailet" v-show="item.isShowDetailet">
            <li v-for="odItem in item.list || []" :key="odItem.id || odItem.foodId">
              <p>{{getFoodName(odItem)}} x {{odItem.quantity || 0}}</p>
              <p>¥{{getFoodTotalPrice(odItem)}}</p>
            </li>
            <li>
              <p>数量</p>
              <p>¥{{item.quantity || 0}}</p>
            </li>
            <!-- 显示评价信息 -->
            <li v-if="item.evaluations && item.evaluations.length > 0" class="evaluation-section">
              <div class="evaluation-header">
                <p><strong>评价信息：</strong></p>
              </div>
              <div v-for="evaluation in item.evaluations" :key="evaluation.id" class="evaluation-item">
                <div class="evaluation-rating">
                  <div class="rating-label-row">
                    <span class="rating-label">评分：</span>
                  </div>
                  <div class="rating-stars-row">
                    <span class="stars">
                      <i v-for="star in 5" :key="star" 
                         :class="star <= evaluation.rating ? 'fa fa-star' : 'fa fa-star-o'"
                         class="star"></i>
                    </span>
                    <span class="rating-text">({{evaluation.rating}}/5)</span>
                  </div>
                </div>
                <div class="evaluation-content">
                  <div class="content-label-row">
                    <strong>评价内容：</strong>
                  </div>
                  <div class="content-text-row">
                    <p>{{evaluation.content || '用户未填写评价内容'}}</p>
                  </div>
                </div>
              
              </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 底部菜单部分 -->
    <Footer v-if="!loading" />

    <!-- 评价弹窗 -->
    <div v-if="showEvaluateDialog" class="evaluate-modal-overlay" @click="closeEvaluateModal">
      <div class="evaluate-modal" @click.stop>
        <div class="modal-header">
          <h3>订单评价</h3>
          <button class="close-btn" @click="closeEvaluateModal">×</button>
        </div>
        
        <div class="modal-body">
          <div class="business-info">
            <h4>{{ currentEvaluateOrder?.business?.businessName || '商家' }}</h4>
            <p class="order-total">订单金额：¥{{ currentEvaluateOrder?.totalPrice || 0 }}</p>
          </div>
          
          <div class="rating-section">
            <label>整体评分</label>
            <div class="star-rating">
              <span 
                v-for="star in 5" 
                :key="star"
                class="star"
                :class="{ active: star <= evaluateForm.rating }"
                @click="setRating(star)"
              >
                ★
              </span>
            </div>
          </div>
          
          <div class="comment-section">
            <label>评价内容</label>
            <textarea 
              v-model="evaluateForm.content"
              placeholder="分享您的用餐体验吧..."
              rows="6"
              maxlength="200"
            ></textarea>
            <div class="char-count">{{ evaluateForm.content.length }}/200</div>
          </div>
        </div>
        
        <div class="modal-footer">
          <div class="footer-buttons">
            <button class="cancel-btn" @click="closeEvaluateModal">取消</button>
            <button class="submit-btn" @click="submitEvaluationNew" :disabled="!evaluateForm.rating">提交评价</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Footer from '../components/Footer.vue';
import { getOrderList, createEvaluation, getEvaluationsByOrderId } from '../api/order';

export default {
  name: 'OrderList',
  data() {
    return {
      orderArr: [],
      user: {},
      loading: true,
      error: false,
      showEvaluateDialog: false,
      currentEvaluateOrder: null,
      evaluateForm: {
        rating: 0,
        content: ''
      }
    }
  },
  created() {
    this.loadOrders();
  },
  methods: {
    loadOrders() {
      this.loading = true;
      this.error = false;
      
      this.user = this.$getSessionStorage('user') || {};
      console.log('当前用户:', this.user);
      
      const userId = this.user.userId || this.user.id;
      if (!userId) {
        console.error('用户ID不存在');
        this.loading = false;
        this.error = true;
        return;
      }
      
      // 使用API调用获取订单列表
      getOrderList({ userId: userId })
      .then(response => {
        console.log('订单API响应:', response);
        const result = response.data.data || [];
        console.log('订单数据:', result);
        
        // 处理订单数据，确保结构完整
        this.orderArr = result.map(item => ({
          ...item,
          isShowDetailet: item.isShowDetailet !== undefined ? item.isShowDetailet : false,
          orderstate: item.status !== undefined ? item.status : 0, // 使用status字段作为订单状态
          business: item.business || { businessName: item.name || '未知商家' },
          list: item.list || [],
          evaluations: [] // 初始化评价数组
        }));
        
        // 获取所有订单的评价信息
        this.loadAllEvaluations();
        
        this.loading = false;
      })
      .catch(error => {
        console.error('获取订单列表失败:', error);
        this.loading = false;
        this.error = true;
        this.$toast && this.$toast('获取订单列表失败，请稍后再试');
      });
    },
    
    reloadOrders() {
      this.loadOrders();
    },
    
    detailetShow(orders) {
      orders.isShowDetailet = !orders.isShowDetailet;
    },
    
    goPay(item) {
      console.log('去支付:', item);
      // this.$router.push({ name: 'Pay', params: { orderId: item.id } });
    },
    
    filterOrders(state) {
      return (this.orderArr || []).filter(item => {
        // 确保item和orderstate存在
        return item && item.orderstate !== undefined && item.orderstate === state;
      });
    },
    
    getBusinessName(item) {
      return item.business?.businessName || '未知商家';
    },
    
    getFoodName(odItem) {
      return odItem.food?.foodName || '未知商品';
    },
    
    getFoodTotalPrice(odItem) {
      return (odItem.food?.foodPrice || 0) * (odItem.quantity || 0);
    },
    
    // 显示评价弹窗
    showEvaluateModal(item) {
      console.log('评价订单:', item);
      this.currentEvaluateOrder = item;
      this.showEvaluateDialog = true;
      // 重置表单
      this.evaluateForm = {
        rating: 0,
        content: ''
      };
    },

    // 关闭评价弹窗
    closeEvaluateModal() {
      this.showEvaluateDialog = false;
      this.currentEvaluateOrder = null;
      this.evaluateForm = {
        rating: 0,
        content: ''
      };
    },

    // 设置评分
    setRating(rating) {
      this.evaluateForm.rating = rating;
    },

    // 提交新的评价
    async submitEvaluationNew() {
      if (!this.evaluateForm.rating) {
        alert('请选择评分');
        return;
      }

      try {
        // 获取用户信息
        const user = this.$getSessionStorage('user') || {};
        const userId = user.userId || user.id;

        const evaluationData = {
          orderId: this.currentEvaluateOrder.id,
          userId: userId,
          rating: this.evaluateForm.rating,
          content: this.evaluateForm.content.trim(),
          createTime: new Date().toISOString()
        };

        console.log('提交评价到后台:', evaluationData);

        // 调用后台API提交评价
        const response = await createEvaluation(evaluationData);
        
        if (response.data) {
          // 提交成功后重新获取该订单的所有评价信息
          await this.refreshOrderEvaluations(this.currentEvaluateOrder.id);
          
          alert('评价提交成功！');
          this.closeEvaluateModal();
        } else {
          throw new Error('提交失败');
        }
      } catch (error) {
        console.error('提交评价失败:', error);
        alert('评价提交失败，请稍后重试');
      }
    },
    
    // 提交评价
    submitEvaluation(order, evaluation) {
      // 模拟提交评价到后端
      console.log('提交评价:', { orderId: order.id, evaluation });
      
      // 暂时将评价添加到本地订单数据中
      if (!order.evaluations) {
        order.evaluations = [];
      }
      
      // 添加评价ID和时间戳
      evaluation.id = Date.now();
      evaluation.createTime = new Date().toISOString();
      
      order.evaluations.push(evaluation);
      
      // 显示成功提示
      alert('评价提交成功！');
      
      // 这里应该调用后端API保存评价
      // evaluationAPI.createEvaluation({ orderId: order.id, ...evaluation })
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    
    // 加载所有订单的评价信息
    async loadAllEvaluations() {
      try {
        // 为每个订单获取评价信息
        const evaluationPromises = this.orderArr.map(async (order) => {
          try {
            const response = await getEvaluationsByOrderId(order.id);
            const evaluations = response.data || [];
            // 将评价信息添加到订单对象中
            order.evaluations = evaluations;
            return { orderId: order.id, evaluations };
          } catch (error) {
            console.error(`获取订单${order.id}的评价失败:`, error);
            order.evaluations = [];
            return { orderId: order.id, evaluations: [] };
          }
        });
        
        await Promise.all(evaluationPromises);
        console.log('所有订单评价加载完成:', this.orderArr);
      } catch (error) {
        console.error('加载订单评价失败:', error);
      }
    },
    
    // 刷新指定订单的评价信息
    async refreshOrderEvaluations(orderId) {
      try {
        // 找到对应的订单
        const order = this.orderArr.find(item => item.id === orderId);
        if (!order) {
          console.error('未找到对应的订单:', orderId);
          return;
        }
        
        // 重新获取该订单的评价信息
        const response = await getEvaluationsByOrderId(orderId);
        const evaluations = response.data || [];
        
        // 更新订单的评价信息
        order.evaluations = evaluations;
        
        console.log(`订单${orderId}的评价信息已更新:`, evaluations);
      } catch (error) {
        console.error(`刷新订单${orderId}的评价失败:`, error);
      }
    }
  },
  components: {
    Footer
  }
}
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 加载状态 ******************/
.loading {
  padding-top: 40vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
  font-size: 4vw;
}

.spinner {
  width: 12vw;
  height: 12vw;
  border: 2px solid #0097FF;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 1s linear infinite;
  margin-bottom: 4vw;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/****************** 错误状态 ******************/
.error {
  padding-top: 40vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
  font-size: 4vw;
}

.error button {
  margin-top: 4vw;
  padding: 2vw 6vw;
  background-color: #0097FF;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 4vw;
}

/****************** 空状态 ******************/
.empty {
  padding-top: 40vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 4vw;
}

.empty img {
  width: 30vw;
  height: 30vw;
  margin-bottom: 4vw;
  border-radius: 50%;
  opacity: 0.6;
}

/****************** 历史订单列表部分 ******************/
.wrapper h3 {
  margin-top: 12vw;
  box-sizing: border-box;
  padding: 4vw;
  font-size: 4vw;
  font-weight: 300;
  color: #999;
}

.wrapper .order {
  width: 100%;
  padding: 0 3vw;
  box-sizing: border-box;
}

.wrapper .order li {
  width: 100%;
  background-color: #fff;
  margin-bottom: 3vw;
  border-radius: 3px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.wrapper .order li .order-info {
  box-sizing: border-box;
  padding: 3vw 4vw;
  font-size: 4vw;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.wrapper .order li .order-info .order-info-right {
  display: flex;
  align-items: center;
}

.wrapper .order li .order-info .order-info-right .order-info-right-icon {
  background-color: #f90;
  color: #fff;
  border-radius: 3px;
  margin-left: 2vw;
  user-select: none;
  cursor: pointer;
  padding: 1.5vw 4vw;
  font-size: 3.5vw;
}

.wrapper .order li .order-detailet {
  width: 100%;
  background-color: #f8f8f8;
}

.wrapper .order li .order-detailet li {
  width: 100%;
  box-sizing: border-box;
  padding: 2vw 4vw;
  color: #666;
  font-size: 3.5vw;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
  box-shadow: none;
  border-radius: 0;
}

/****************** 底部菜单部分 ******************/
.wrapper Footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

/****************** 评价弹窗样式 ******************/
.evaluate-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  padding: 4vw;
}

.evaluate-modal {
  background: white;
  border-radius: 12px;
  width: 100%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4vw 5vw;
  border-bottom: 1px solid #eee;
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  color: white;
  border-radius: 12px 12px 0 0;
}

.modal-header h3 {
  margin: 0;
  font-size: 4.5vw;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 6vw;
  cursor: pointer;
  padding: 0;
  width: 8vw;
  height: 8vw;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.modal-body {
  padding: 5vw;
  display: flex;
  flex-direction: column;
  gap: 4vw;
}

.business-info {
  text-align: center;
  padding: 4vw;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-radius: 8px;
  border-left: 4px solid #ff6b35;
}

.business-info h4 {
  margin: 0 0 2vw 0;
  font-size: 4.2vw;
  color: #333;
  font-weight: 600;
}

.order-total {
  margin: 0;
  font-size: 3.8vw;
  color: #ff6b35;
  font-weight: 500;
}

.rating-section, .comment-section {
  display: flex;
  flex-direction: column;
  gap: 3vw;
}

.rating-section label, .comment-section label {
  font-size: 4vw;
  color: #333;
  font-weight: 500;
  margin: 0;
}

.star-rating {
  display: flex;
  gap: 1vw;
  justify-content: center;
  margin-bottom: 3vw;
}

.star {
  font-size: 8vw;
  color: #ddd;
  cursor: pointer;
  transition: all 0.2s ease;
  user-select: none;
}

.star:hover {
  transform: scale(1.1);
}

.star.active {
  color: #ffd700;
  text-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
}

.comment-section textarea {
  width: 100%;
  border: 2px solid #eee;
  border-radius: 8px;
  padding: 3vw;
  font-size: 3.8vw;
  resize: vertical;
  min-height: 20vw;
  box-sizing: border-box;
  transition: border-color 0.2s;
  font-family: inherit;
}

.comment-section textarea:focus {
  outline: none;
  border-color: #ff6b35;
  box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.1);
}

.char-count {
  text-align: right;
  font-size: 3.2vw;
  color: #999;
  margin-top: 1vw;
}

.modal-footer {
  padding: 4vw 5vw;
  border-top: 1px solid #eee;
  background: #f8f9fa;
  border-radius: 0 0 12px 12px;
}

.footer-buttons {
  display: flex;
  gap: 3vw;
  width: 100%;
}

.cancel-btn, .submit-btn {
  flex: 1;
  padding: 3.5vw;
  border: none;
  border-radius: 6px;
  font-size: 4vw;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 500;
}

.cancel-btn {
  background: #6c757d;
  color: white;
}

.cancel-btn:hover {
  background: #5a6268;
}

.submit-btn {
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #e55a2b, #e8851a);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 53, 0.3);
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}



.evaluate-btn {
  background-color: #FF6000 !important;
  color: #fff !important;
  font-size: 3.5vw !important;
  padding: 1.5vw 3vw !important;
  border-radius: 3px !important;
  cursor: pointer;
  margin-left: 2vw;
}

.evaluate-btn:hover {
  background-color: #e55a00 !important;
}

.evaluation-section {
  background-color: #f8f9fa !important;
  border-top: 1px solid #e9ecef;
  margin-top: 2vw;
  padding: 3vw !important;
}

.evaluation-header p {
  color: #333 !important;
  font-size: 4vw !important;
  margin-bottom: 2vw !important;
}

.evaluation-item {
  background-color: #fff;
  border-radius: 3px;
  padding: 3vw;
  margin-bottom: 2vw;
  border-left: 3px solid #FF6000;
}

.evaluation-rating {
  margin-bottom: 2vw;
}

.rating-label-row {
  margin-bottom: 1vw;
}

.rating-label {
  font-size: 3.5vw;
  color: #666;
}

.rating-stars-row {
  display: flex;
  align-items: center;
}

.stars {
  margin-right: 2vw;
}

.star {
  color: #FFD700;
  font-size: 3.5vw;
  margin-right: 0.5vw;
}

.rating-text {
  font-size: 3vw;
  color: #999;
}

.evaluation-content {
  margin-bottom: 2vw;
}

.content-label-row {
  margin-bottom: 1vw;
}

.content-label-row strong {
  font-size: 3.5vw;
  color: #666;
}

.content-text-row p {
  font-size: 3.5vw !important;
  color: #333 !important;
  line-height: 1.4;
  margin: 0 !important;
}

.evaluation-time .time-text {
  font-size: 3vw !important;
  color: #999 !important;
  margin: 0 !important;
}
</style>